<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  nextTick,
  onMounted,
  ref,
  watch,
  watchEffect,
} from 'vue'
import { Message } from 'element-ui'
import AnnualDetailTable from '@/views/project-update/annual-plan/detail-table.vue'
import MonthReportDetailTable from '@/views/project-update/month-report/detail-table.vue'
import ProjectDetailTable from '@/views/project-update/inventory-review/project-inventory/detail-table.vue'
import AreaDetailTable from '@/views/project-update/inventory-review/area-storage/detail-table.vue'
import Building from '@/components/building/Building.vue'
import baseTable from '@/components/base-table/index.vue'
import CommonLayoutTable from '@/views/project-update/library-manage/common-layout-table.vue'
import ApplyTable from '@/views/project-update/library-manage/applyTable.vue'
import { queryArea } from '@/api/question'
import { getAnnualPlan } from '@/api/project-update/annual-plan'
import { getMonthReport } from '@/api/project-update/month-report'
import { getProjectLedgerTotalDetail } from '@/api/project-update/project-ledger'
import {
  buildRenderTables,
  investRenderTables,
  operationRenderTables,
} from '@/views/project-update/library-manage/edit-table-info'
import { projectStageQuery } from '@/api/project-update/stage-info'
import { getSubProjectInventoryList } from '@/api/project-update/sub-project-inventory'
import { getMonth } from '@/api/project-update/select'

const vm = getCurrentInstance()

const route = vm.proxy.$route
const router = vm.proxy.$router
const currentUser = vm.proxy.$store.state.user.currentUser
const userLevel = JSON.parse(localStorage.getItem('user') || '{}')?.user
  ?.roleLevel

const handleCancel = () => {
  router.go(-1)
}

const params = route.query
const { pkid, es: status, district, name } = params

const regionList = ref([])

const getAreaInfo = async () => {
  try {
    const res = await queryArea({})
    if (res.success) {
      regionList.value = res.data[0].children
      if (district) {
        regionId.value = regionList.value.find(
          (item) => item.areaName === district
        ).pkid
      }
    }
  } catch (error) {
    Message.error(error.message)
  }
}

const regionId = ref('')

const activeName = ref('project-info')

const yearList = ref([])

const monthList = ref([])

const checkedYear = ref('')
const checkedMonth = ref('')

watch(
  () => checkedYear.value,
  (val) => {
    console.log(val)
    const year = yearList.value.find((item) => item.value === val)
    monthList.value = year?.months || []
    console.log(monthList)
    checkedMonth.value = monthList.value[0]?.value
  }
)

const page = ref({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const tableCols = ref([
  {
    prop: 'subPeName',
    label: '子项目名称',
  },
  {
    label: '是否入统',
    prop: 'isRt',
  },
  {
    label: '入统行业代码',
    prop: 'rtCode',
  },
  {
    prop: 'createTime',
    label: '入库时间',
  },
])

const tableData = ref([])

const checkedStage = ref('实施阶段')

const stageList = ref([
  {
    label: '实施阶段',
    value: '实施阶段',
  },
  {
    label: '运营阶段',
    value: '运营阶段',
  },
])

const areaDetailTableRef = ref(null)

const areaDetailTablePkid = ref('')

const changeRegionId = (id) => {
  if (!id) return
  regionId.value = id
}

const annualDetailInfoList = ref([])

const annualDetailTableRef = ref(null)

const getAnnualPlanList = () => {
  getAnnualPlan({ projectId: pkid }).then((res) => {
    if (res.success) {
      if (!res.data) {
        return
      }
      let years = res.data.map((item) => item.year)
      years = Array.from(new Set(years))
      annualDetailInfoList.value = years.map((year) => {
        const data = res.data.filter((item) => item.year === year)
        return {
          year,
          data,
        }
      })
      nextTick(() => {
        years.forEach((_, index) => {
          annualDetailTableRef.value[index]?.inputData(
            annualDetailInfoList.value[index].data
          )
        })
      })
    } else {
      Message.error(res.message)
    }
  })
}

const monthReportDetailTableRef = ref(null)

const getMonthReportList = () => {
  getProjectLedgerTotalDetail({
    projectId: pkid,
    regionId: regionId.value,
    year: checkedYear.value,
    month: checkedMonth.value,
  }).then((res) => {
    if (res.success) {
      monthReportDetailTableRef.value.inputData(res.data[0])
    } else {
      Message.error(res.message)
    }
  })
}

watchEffect(() => {
  if (checkedYear.value && checkedMonth.value) {
    getMonthReportList()
  }
})

const editableTabs = ref([])
const editableTabsValue = ref('')
const editableOperateTabs = ref([])
const editableOperateTabsValue = ref('')
const implementStageInfoList = ref([])
const manageStageInfoList = ref([])
const buildTableRef = ref(null)
const projectTableRef = ref(null)
const manageTableRef = ref(null)

const getFormData = () => {
  const currentYear = editableTabsValue.value
  const iF =
    implementStageInfoList.value.find((item) => item.year == currentYear) || {}
  buildTableRef.value?.inputData(iF)
  projectTableRef.value?.inputData(iF)
}

const getFormOperateData = () => {
  const currentYear = editableOperateTabsValue.value
  const mF =
    manageStageInfoList.value.find((item) => item.year == currentYear) || {}
  manageTableRef.value?.inputData(mF)
}

const getDetail = () => {
  projectStageQuery({ projectId: pkid })
    .then((res) => {
      if (res.success) {
        if (res.data) {
          console.log('editableOperateTabsValue.value--', res.data)
          const { implementStageInfoList: iL, manageStageInfoList: mL } =
            res.data
          implementStageInfoList.value = iL
          manageStageInfoList.value = mL
          editableTabs.value = []
          editableTabsValue.value = ''
          if (iL.length) {
            iL.forEach((item) => {
              if (item.year) {
                editableTabs.value.push({
                  title: item.year?.toString(),
                  name: item.year?.toString(),
                })
              }
            })
            editableTabsValue.value = iL[0].year + ''
          }
          
          editableOperateTabs.value = []
          editableOperateTabsValue.value = ''
          if (mL.length) {
            mL.forEach((item) => {
            if (item.year) {
                editableOperateTabs.value.push({
                  title: item.year?.toString(),
                  name: item.year?.toString(),
                })
              }
            })
            editableOperateTabsValue.value = mL[0].year + ''
          }
        } else {
          editableTabsValue.value = ''
          editableTabs.value = []
          editableOperateTabsValue.value = ''
          editableOperateTabs.value = []
        }
      } else {
        Message.error(res.message)
      }
    })
    .catch((e) => {
      editableTabsValue.value = ''
      editableTabs.value = []
      editableOperateTabsValue.value = ''
      editableOperateTabs.value = []
    })
}

watch(
  () => editableTabsValue.value,
  (val) => {
    if (val) {
      getFormData()
    }
  }
)

watch(
  () => editableOperateTabsValue.value,
  (val) => {
    if (val) {
      getFormOperateData()
    }
  }
)

const getSubProjectTableData = () => {
  getSubProjectInventoryList({ ...page.value, projectId: pkid }).then((res) => {
    if (res.success) {
      tableData.value = res.data.list?.map((item) => {
        return {
          ...item,
          isRt: item.isRt === 'Y' ? '是' : '否',
        }
      })
      page.value.total = res.data.count
    } else {
      Message.error(res.message)
    }
  })
}

const getYearOptions = () => {
  getMonth({
    projectId: pkid,
  }).then((res) => {
    if (res.success) {
      const data =
        res.data?.map((item, index) => {
          const { 0: year, 1: month } = item.split('-')
          if (index === 0) {
            checkedYear.value = year
          }
          return {
            year,
            month,
          }
        }) || []
      const years = Array.from(new Set(data.map((item) => item.year)))
      yearList.value = years.map((year) => {
        return {
          value: year,
          label: year + '年',
          months: data
            .filter((item) => item.year === year)
            .map((item) => {
              return {
                label: item.month + '月',
                value: item.month,
              }
            }),
        }
      })
    }
  })
}

onMounted(async () => {
  await getAreaInfo()
  await getYearOptions()
  // console.log(regionId)
  getAnnualPlanList()
  getDetail()
  getSubProjectTableData()
})

const handleChangeAreaId = (id) => {
  areaDetailTablePkid.value = id
  if (id) {
    areaDetailTableRef.value?.initData(id)
  }
}
</script>

<template>
  <div class="add-annual-plan show-detail-form">
    <div class="nav">
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/project-update/library-manage' }"
            ><span class="breadcrumb-title">列表</span></el-breadcrumb-item
          >
          <el-breadcrumb-item>详情</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    <div class="content">
      <div class="content-main">
        <el-tabs v-model="activeName">
          <el-tab-pane label="项目信息" name="project-info">
            <project-detail-table
              :disabled="true"
              :user-level="userLevel"
              :pkid="pkid"
              @changeAreaId="handleChangeAreaId"
            />
          </el-tab-pane>
          <el-tab-pane label="阶段信息" name="stage-info">
            <div class="stage-select">
              <el-radio-group v-model="checkedStage">
                <el-radio-button
                  v-for="stage in stageList"
                  :key="stage.value"
                  :label="stage.value"
                ></el-radio-button>
              </el-radio-group>
              <el-tabs v-model="editableTabsValue" v-if="checkedStage === '实施阶段'">
                <el-tab-pane
                  :key="item.name"
                  v-for="item in editableTabs"
                  :label="item.title"
                  :name="item.name"
                >
                </el-tab-pane>
              </el-tabs>
              <el-tabs v-model="editableOperateTabsValue" v-if="checkedStage === '运营阶段'">
                <el-tab-pane
                  :key="item.name"
                  v-for="item in editableOperateTabs"
                  :label="item.title"
                  :name="item.name"
                >
                </el-tab-pane>
              </el-tabs>
            </div>
            <div
              class="stage-detail-table"
              v-show="checkedStage === '实施阶段'"
            >
              <div v-show="editableTabs.length">
                <div class="common-title">
                  <i class="title-icon"></i>
                  <span>项目建设情况</span>
                </div>
                <common-layout-table
                  :render-tables="buildRenderTables"
                  ref="buildTableRef"
                  :disabled="true"
                />
                <div class="common-title">
                  <i class="title-icon"></i>
                  <span>项目投资情况</span>
                </div>
                <common-layout-table
                  :render-tables="investRenderTables"
                  ref="projectTableRef"
                  :disabled="true"
                />
              </div>
              <div v-show="!editableTabs.length" class="no-data">
                <div class="no-data-icon"></div>
                <div class="no-data-text">暂无数据</div>
              </div>
            </div>
            <div
              class="stage-detail-table"
              v-show="checkedStage === '运营阶段'"
            >
              <div v-show="editableOperateTabs.length">
                <div class="common-title">
                  <i class="title-icon"></i>
                  <span>项目运营情况</span>
                </div>
                <common-layout-table
                  :render-tables="operationRenderTables"
                  ref="manageTableRef"
                  :disabled="true"
                />
              </div>
              <div v-show="!editableOperateTabs.length" class="no-data">
                <div class="no-data-icon"></div>
                <div class="no-data-text">暂无数据</div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="年度计划" name="annual-plan">
            <template v-for="(item, index) in annualDetailInfoList">
              <div class="common-title" :key="index + 'title'">
                <i class="title-icon"></i>
                <span>{{ item.year }}{{ district }}城市更新年度计划表</span>
              </div>
              <annual-detail-table
                ref="annualDetailTableRef"
                :region-list="regionList"
                :region-id="regionId"
                :status="status"
                :key="index"
              />
            </template>
          </el-tab-pane>
          <el-tab-pane label="项目月报" name="”month-report”">
            <div class="year-select">
              年度：
              <el-radio-group v-model="checkedYear">
                <el-radio-button
                  v-for="year in yearList"
                  :key="year.value"
                  :label="year.value"
                ></el-radio-button>
              </el-radio-group>
            </div>
            <div class="month-select">
              月份：
              <el-radio-group v-model="checkedMonth">
                <el-radio-button
                  v-for="month in monthList"
                  :key="month.value"
                  :label="month.value"
                ></el-radio-button>
              </el-radio-group>
            </div>
            <month-report-detail-table
              v-show="checkedYear"
              ref="monthReportDetailTableRef"
              :status="status"
              :y="checkedYear"
              :m="checkedMonth"
              :r-n="district"
            />
          </el-tab-pane>
          <el-tab-pane label="片区信息" name="area-info">
            <area-detail-table
              ref="areaDetailTableRef"
              @changeRegionId="changeRegionId"
              :pkid="areaDetailTablePkid"
              :region-id="regionId"
              :region-list="regionList"
              :user-level="userLevel"
              :disabled="true"
            />
          </el-tab-pane>
          <el-tab-pane label="子项目信息" name="sub-project-info">
            <baseTable :page.sync="page" :cols="tableCols" :data="tableData">
              <template #head>
                <div class="head"></div>
              </template>
            </baseTable>
          </el-tab-pane>
          <el-tab-pane label="流转、变更记录" name="transfer-record">
            <apply-table :pkid="pkid" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="buttons">
        <el-button class="cancel" @click="handleCancel">取消</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.add-annual-plan {
  width: calc(100% - 40px);
  height: calc(100% - 40px);
  padding: 20px;
  background-color: rgba(244, 248, 254, 1);

  .content {
    width: calc(100% - 40px);
    height: calc(100% - 70px);
    position: absolute;
    top: 65px;
    bottom: 0;

    .divider {
      width: 100%;
      height: 1px;
      background: #e7f0ff;
      border-radius: 1px 1px 0px 0px;
      margin: 20px 0;
    }

    .content-main {
      height: calc(100% - 100px);
      background: #ffffff;
      box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);
      border-radius: 2px;
      padding: 13px 16px 13px 16px;
      overflow-y: auto;

      .common-title {
        margin: 10px 0;
        padding: 0px 0 2px 5px;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: bold;
        color: #000000;
        display: flex;
        align-items: center;

        > span {
          margin-left: 5px;
        }

        .title-icon {
          width: 5px;
          height: 16px;
          background: #10a6dd;
          border-radius: 3px;
          margin-right: 4px;
        }
      }

      .year-select {
        margin: 10px 0;
        display: flex;
        font-size: 14px;
        align-items: center;

        .el-radio-group {
          margin-left: 10px;
        }
      }

      .month-select {
        margin: 10px 0;
        display: flex;
        align-items: center;
        font-size: 14px;

        .el-radio-group {
          margin-left: 10px;
        }
      }

      .stage-select {
        display: flex;

        .el-radio-group {
          margin-right: 20px;
        }
      }

      :deep(.el-tabs) {
        height: 100%;

        .el-tabs__content {
          height: calc(100% - 60px);

          .el-tab-pane {
            padding: 0;
            height: 100%;
            overflow-y: auto;
          }

          .basetable-content {
            padding: 0 !important;

            .el-table {
              margin-top: 0 !important;
              height: 100%;
            }
          }

          .basetable-footer {
            bottom: 0;
            margin: 0;
          }
        }
      }
    }

    .buttons {
      padding: 10px;
      display: flex;
      justify-content: center;
      background: #ffffff;
      box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);

      .el-button {
        width: 110px;
      }

      .cancel {
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #e7f0ff;
        font-weight: 400;
        font-size: 16px;
        color: #8894a8;
      }

      .save {
        //background: #10a6dd;
        border-radius: 4px;
        //color: #ffffff;
      }

      .publish {
        //background: #ffffff;
        border-radius: 4px;
        //color: #10a6dd;
        //border: 1px solid #10a6dd;
      }
    }
  }

  .no-data {
    &-icon {
      background-size: 100% 100%;
      background-repeat: no-repeat;
      background-image: url('~@/assets/empty.png');
      width: 400px;
      height: 300px;
      margin: 0 auto;
    }
    
    &-text {
      display: flex;
      justify-content: center;
      margin: 0 auto;
      margin-top: 10px;
      color: rgba(0,0,0, 0.4)
    }
  }
}
</style>
